<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="订单号/客户"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.status" placeholder="订单状态" clearable style="width: 120px" class="filter-item">
        <el-option label="待付款" value="pending" />
        <el-option label="已付款" value="paid" />
        <el-option label="已完成" value="completed" />
        <el-option label="已取消" value="cancelled" />
      </el-select>
      <el-date-picker
        v-model="listQuery.dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="filter-item"
        style="width: 350px;"
        value-format="yyyy-MM-dd"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="success" icon="el-icon-plus" @click="handleCreate">
        新建订单
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="订单号" width="180">
        <template slot-scope="scope">
          {{ scope.row.orderNo }}
        </template>
      </el-table-column>
      <el-table-column label="客户" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.customer }}
        </template>
      </el-table-column>
      <el-table-column label="金额" width="120" align="center">
        <template slot-scope="scope">
          ¥{{ scope.row.amount }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleDetail(row)">
            详情
          </el-button>
          <el-button v-if="row.status === 'pending'" size="mini" type="success" @click="handlePay(row)">
            付款
          </el-button>
          <el-button v-if="row.status === 'paid'" size="mini" type="success" @click="handleComplete(row)">
            完成
          </el-button>
          <el-button v-if="row.status === 'pending'" size="mini" type="danger" @click="handleCancel(row)">
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog title="订单详情" :visible.sync="detailDialogVisible" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="客户">{{ currentOrder.customer }}</el-descriptions-item>
        <el-descriptions-item label="金额">¥{{ currentOrder.amount }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ currentOrder.remark }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="currentOrder.items" style="margin-top: 20px" border>
        <el-table-column label="商品名称" prop="productName" />
        <el-table-column label="单价" width="120" align="center">
          <template slot-scope="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120" align="center" prop="quantity" />
        <el-table-column label="小计" width="120" align="center">
          <template slot-scope="scope">
            ¥{{ scope.row.price * scope.row.quantity }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="新建订单" :visible.sync="createDialogVisible" width="800px">
      <el-form ref="orderForm" :model="orderForm" :rules="rules" label-width="100px">
        <el-form-item label="客户" prop="customer">
          <el-input v-model="orderForm.customer" />
        </el-form-item>
        <el-form-item label="商品">
          <el-table :data="orderForm.items" border>
            <el-table-column label="商品" width="300">
              <template slot-scope="scope">
                <el-select v-model="scope.row.productId" placeholder="选择商品" @change="handleProductChange($event, scope.$index)">
                  <el-option
                    v-for="item in productOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="单价" width="120" align="center">
              <template slot-scope="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column label="数量" width="120" align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.quantity" :min="1" @change="calculateTotal" />
              </template>
            </el-table-column>
            <el-table-column label="小计" width="120" align="center">
              <template slot-scope="scope">
                ¥{{ scope.row.price * scope.row.quantity }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeItem(scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px">
            <el-button type="primary" icon="el-icon-plus" @click="addItem">添加商品</el-button>
          </div>
        </el-form-item>
        <el-form-item label="总金额">
          <span class="total-amount">¥{{ orderForm.amount }}</span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="orderForm.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createOrder">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSalesList, getSaleDetail, createSale, updateSaleStatus } from '@/api/sales'
import { getProductList } from '@/api/products'
import Pagination from '@/components/Pagination'

export default {
  name: 'SalesList',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: undefined,
        status: undefined,
        dateRange: []
      },
      detailDialogVisible: false,
      createDialogVisible: false,
      currentOrder: {},
      productOptions: [],
      orderForm: {
        customer: '',
        items: [],
        amount: 0,
        remark: ''
      },
      rules: {
        customer: [{ required: true, message: '请输入客户名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getProducts()
  },
  methods: {
    async getList() {
      this.listLoading = true
      try {
        const { data } = await getSalesList(this.listQuery)
        this.list = data.items
        this.total = data.total
      } finally {
        this.listLoading = false
      }
    },
    async getProducts() {
      try {
        const { data } = await getProductList({ limit: 1000 })
        this.productOptions = data.items
      } catch (error) {
        console.error('获取商品列表失败:', error)
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getStatusType(status) {
      const statusMap = {
        pending: 'warning',
        paid: 'primary',
        completed: 'success',
        cancelled: 'info'
      }
      return statusMap[status]
    },
    getStatusText(status) {
      const statusMap = {
        pending: '待付款',
        paid: '已付款',
        completed: '已完成',
        cancelled: '已取消'
      }
      return statusMap[status]
    },
    async handleDetail(row) {
      try {
        const { data } = await getSaleDetail(row.id)
        this.currentOrder = data
        this.detailDialogVisible = true
      } catch (error) {
        console.error('获取订单详情失败:', error)
      }
    },
    handleCreate() {
      this.orderForm = {
        customer: '',
        items: [],
        amount: 0,
        remark: ''
      }
      this.createDialogVisible = true
    },
    addItem() {
      this.orderForm.items.push({
        productId: '',
        productName: '',
        price: 0,
        quantity: 1
      })
    },
    removeItem(index) {
      this.orderForm.items.splice(index, 1)
      this.calculateTotal()
    },
    handleProductChange(productId, index) {
      const product = this.productOptions.find(p => p.id === productId)
      if (product) {
        this.orderForm.items[index].productName = product.name
        this.orderForm.items[index].price = product.price
        this.calculateTotal()
      }
    },
    calculateTotal() {
      this.orderForm.amount = this.orderForm.items.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    },
    createOrder() {
      this.$refs.orderForm.validate(async (valid) => {
        if (valid) {
          if (this.orderForm.items.length === 0) {
            this.$message.warning('请添加商品')
            return
          }
          try {
            await createSale(this.orderForm)
            this.createDialogVisible = false
            this.$notify({
              title: '成功',
              message: '创建订单成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          } catch (error) {
            console.error('创建订单失败:', error)
          }
        }
      })
    },
    handlePay(row) {
      this.$confirm('确认该订单已付款?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await updateSaleStatus(row.id, 'paid')
          row.status = 'paid'
          this.$notify({
            title: '成功',
            message: '订单状态已更新',
            type: 'success',
            duration: 2000
          })
        } catch (error) {
          console.error('更新订单状态失败:', error)
        }
      })
    },
    handleComplete(row) {
      this.$confirm('确认完成该订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await updateSaleStatus(row.id, 'completed')
          row.status = 'completed'
          this.$notify({
            title: '成功',
            message: '订单状态已更新',
            type: 'success',
            duration: 2000
          })
        } catch (error) {
          console.error('更新订单状态失败:', error)
        }
      })
    },
    handleCancel(row) {
      this.$confirm('确认取消该订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await updateSaleStatus(row.id, 'cancelled')
          row.status = 'cancelled'
          this.$notify({
            title: '成功',
            message: '订单已取消',
            type: 'success',
            duration: 2000
          })
        } catch (error) {
          console.error('取消订单失败:', error)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .filter-container {
    padding-bottom: 10px;
    .filter-item {
      display: inline-block;
      vertical-align: middle;
      margin-bottom: 10px;
      margin-right: 10px;
    }
  }

  .total-amount {
    font-size: 20px;
    color: #f56c6c;
    font-weight: bold;
  }
}
</style> 